'use client'
import React, { useState, createContext, useContext } from 'react';
import Header from './Header';
import Footer from './Footer';
import { Category } from '@/types/category';

// 创建一个Context来共享状态
interface AppContextType {
  currentCategory: Category | null;
  searchQuery: string;
  setCurrentCategory: (category: Category | null) => void;
  setSearchQuery: (query: string) => void;
}

const AppContext = createContext<AppContextType | undefined>(undefined);

// 自定义Hook以便子组件使用Context
//
// 挂载Context Provider  为全局都可以使用。
export const useAppContext = () => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useAppContext must be used within an AppLayout');
  }
  return context;
};

interface AppLayoutProps {
  children: React.ReactNode;
}

export default function AppLayout({ children }: AppLayoutProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [currentCategory, setCurrentCategory] = useState<Category | null>(null);

  // 搜索处理函数
  const handleSearch = (query: string) => {
    setSearchQuery(query);
  };

  // 分类切换处理函数
  const handleCategoryChange = (category: Category | null) => {
    setCurrentCategory(category);
  };


  const contextValue: AppContextType = {
    currentCategory,
    searchQuery,
    setCurrentCategory,
    setSearchQuery
  };

  return (
    <AppContext.Provider value={contextValue}>
      <div className="flex flex-col min-h-screen">
        <Header 
          onSearch={handleSearch} 
          onCategoryChange={handleCategoryChange}
          currentCategory={currentCategory}
        />
        <main className="flex-1 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {children}
        </main>
        <Footer />
      </div>
    </AppContext.Provider>
  );
}